let MemberAppJs = {};

try {
  MemberAppJs = window.MemberAppJs;
  if (!MemberAppJs) {
    MemberAppJs = window.memberApp;
  }
} catch (e1) {
  try {
    MemberAppJs = window.memberApp;
  } catch (e2) {
    console.log(e1); // eslint-disable-line
    console.log(e2); // eslint-disable-line
  }
}

const protocol = 'js-call://';
const isAndroidPlatform = navigator.userAgent.match(/android/ig);
const isApplePlatform = navigator.userAgent.match(/iphone|ipod|ipad/ig);

function proxyCallback(callback) {
  const methodName = `__app_cb_${Date.now()}`;

  window[methodName] = (rs) => {
    callback(rs);
    delete window[methodName];
  };

  return methodName;
}

/**
 * scanQRCode
 *
 * @param {number} 1:二维码 2:条形码
 */
export function scanQRCode(type) {
  return new Promise((resolve, reject) => {
    const cb = proxyCallback((rs) => resolve(rs));
    if (isApplePlatform) {
      document.location.href = `${protocol}scanQrBarCode/${type}/${cb}`;
    } else if (isAndroidPlatform) {
      MemberAppJs.scanQrBarCode(type, cb);
    } else {
      reject();
    }
  });
}

/**
 * Close Window
 * @return {[type]} [description]
 */
export function close() {
  if (isApplePlatform) {
    document.location.href = 'js-back://memberApp/memberApp.backToActivityMenu';
  } else if (isAndroidPlatform) {
    MemberAppJs.backToActivityMenu();
  }
}

export default {};
